<?php
namespace Crm\Domain;

use Crm\Common\MetaData as MetaData;
use Crm\Common\Util as Util;
use Crm\Common\Pager as Pager;

class Esf
{
	/**
	 * pdo连接。
	 * 
	 * @var object
	 * @access pdo
	 */
	public $pdo;

    public $metaData;
    public $baseCode;
    public $city_code;
    public $provinceCode;
    public $borough_option;//行政区
    public $pm_level_option;
    public $look_way_option;//看房方式
    public $house_status_option;//房屋现状
    public $house_level_option;//房源等级
    public $property_status_option; //产权状态
    public $property_nature_option; //产权性质(个人、公司等)
    public $origin_option; //来源渠道
    public $toward_option; //房屋朝向
    public $fitment_type_option; //内部装修
    public $build_year_option;//建筑年代
    public $pic_option;// 图片类型
    public $cost_detail_option;//费用明细
    public $facilities_option;//内部配套
    public $sale_point_option;//房屋卖点
    public $subject_option;//跟进主题

    public $is_follow;//用户是否需要填写跟进
    public $is_esf_owner_super=0;//当该房源不属于自己时,判断前用户是否是该房源拥有者上级


    public function __construct()
    {
        $params = \PhalApi\DI()->request->getAll();
        $house_type =  trim(isset($params["house_type"])?$params["house_type"]:'1');
        $property_nature_code = $house_type==1?218:216;

        $this->pdo = \PhalApi\DI()->pdo;
        $this->baseCode = (object)\PhalApi\DI()->config->get('basecode');
        $this->province_code = \PhalApi\DI()->config->get('app.provinceCode');//省
        $this->city_code = \PhalApi\DI()->config->get('app.cityCode');//城市

        $this->metaData = new MetaData();

        $this->borough_option = $this->metaData->getPairBaseCodeByType($this->city_code);//区域列表
        $this->pm_level_option = $this->metaData->getPairBaseCodeByType(223);//物业等级
        $this->look_way_option = $this->metaData->getPairBaseCodeByType(226);//看房方式
        $this->house_status_option = $this->metaData->getPairBaseCodeByType(220);//房屋现状
        $this->house_level_option  = $this->metaData->getPairBaseCodeByType(242);//房源等级
        $this->property_status_option = $this->metaData->getPairBaseCodeByType(227);
        $this->property_nature_option = $this->metaData->getPairBaseCodeByType($property_nature_code);
        $this->origin_option     = $this->metaData->getPairBaseCodeByType(10101);
        $this->toward_option   = $this->metaData->getPairBaseCodeByType(215);
        $this->fitment_type_option    = $this->metaData->getPairBaseCodeByType(219);
        $this->build_year_option      = $this->metaData->getPairBaseCodeByType(229);
        $this->pic_option             = $this->metaData->getPairBaseCodeByType(210);
        $this->cost_detail_option     = $this->metaData->getPairBaseCodeByType(231);
        $this->sale_point_option      = $this->metaData->getPairBaseCodeByType(233);
        $this->subject_option         = $this->metaData->getPairBaseCodeByType(241,' order by sort desc',false);
    }

    public function search($user){
        $this->session = (object)$user;
        $data = \PhalApi\DI()->request->getAll();
        $tpl = isset($data['tpl'])?$data['tpl']:'list';
        $view = isset($data['view'])?$data['view']:'list';
        $by = trim(isset($data["by"])?$data["by"]:'all');
        $flag = trim(isset($data["flag"])?$data["flag"]:'1');
        $house_type  = trim(isset($data["house_type"])?$data["house_type"]:1);
        if($house_type==1){
            $header="出租";
            $price_unit = '元/月';
            $unit_price_unit = '元/m²·月';
            $this->baseCode->price = $this->baseCode->price_option;
        }else{
            $header="出售";
            $price_unit = '万';
            $unit_price_unit = '元/m²';
            $this->baseCode->price = $this->baseCode->price_total_option;
        }
        if($flag==0)$header="回收站";
        $page_info ="house_type=".$house_type."&";
        $order = isset($data['order']) ? $data['order'] : 'a.house_level asc,a.create_date desc';
        $pageSize = isset($data['pageSize']) ? $data['pageSize'] : ' 30';
        $offset = 0;
        $subPages=5;//每次显示的页数
        $currentPage = isset($data['page']) ? (int)$data['page'] : 0;
        if($currentPage>0) $offset=($currentPage-1)*$pageSize;
        $where = 'where a.house_type='.$house_type;

        $filter = array();//筛选条件
        $filter['tpl'] = $tpl;
        $filter['by'] = $by;
        $filter['sort'] = $order;
        $filter['house_type'] = $house_type;
        $page_info .="order=".$order."&by=".$by."&tpl=".$tpl."&page=".$currentPage."&";

        $sysUser = new SysUser();
        //视图
        switch($by) {
            //case 'today' : $where .= ' create_date='.strtotime(date('Y-m-d', time())) ; break;
            //case 'week' : $where['create_time'] =  array('gt',(strtotime(date('Y-m-d')) - (date('N', time()) - 1) * 86400)); break;
            //case 'month' : $where['create_time'] = array('gt',strtotime(date('Y-m-01', time()))); break;
            //case 'add' : $order = 'create_time desc'; break;
            //case 'update' : $order = 'update_time desc'; break;
            case 'sub' :
                //$below_ids = $sysUser->getSubUserIdByUserId($this->session->user_id,0);
                $dep_ids = $sysUser->getUserListByDepartmentId($this->session->department_id,'key');
                $below_ids_str = implode(',',$dep_ids);
                $where .= " and a.owner_uid in (". $this->session->user_id . "," . $below_ids_str .") ";
                $filter['by_val'] = '我部门的';
                break;
            //case 'deleted' : $where['is_deleted'] = 1;break;
            case 'me' :
                $where .= " and a.owner_uid=".$this->session->user_id." ";
                $filter['by_val'] = '我的';
                break;
            //case 'focus' : $where['customer_id'] = array('in',$focus_id);break;
            //case 'share' : $where['customer_id'] = array('in',$customerid);break;
            //case 'myshare' : $where['customer_id'] = array('in',$share_customer_ids);break;
            case 'resource':
                if($this->baseCode->esf->is_out){
                    //房源池类型1部门房源池2公共房源池
                    $resource_type = isset($data['resource_type'])?$data['resource_type']:'2';
                    $filter['resource_type'] = $resource_type;
                    $page_info .= "resource_type=".$resource_type."&";
                    $warn_outdate = time()-(86400*$this->baseCode->esf->warn_outdays);
                    $danger_outdate = time()-(86400*$this->baseCode->esf->danger_outdays);
                    if($resource_type==1){
                        $dep_ids = $sysUser->getUserListByDepartmentId($this->session->department_id,'key');
                        $dep_ids_str = implode(',',$dep_ids);
                        //部门房源池[此处有个需要优化的地方: 当其他部门的人把房源手动放入客户池,则在部门房源池可以看到其他部门的房源]
                        $where .= " and a.owner_uid=0 or (a.log_date <= ".$warn_outdate." and a.log_date >= ".$danger_outdate.")";
                        if(empty($dep_ids_str)) {
                            $where .= " and a.owner_uid =" . $this->session->user_id;
                        }else {
                            $where .= " and a.owner_uid in (" . $this->session->user_id . "," . $dep_ids_str . ")";
                        }
                    }else{
                        //公共房源池
                        $where .= " and (a.owner_uid=0 or a.log_date <= ".$danger_outdate.")";
                    }
                }else {
                    $where .= " and a.owner_uid=0 ";
                }
                $header ='房源池';
                break;
            case 'all':
                $where .= " and a.owner_uid>0 ";
                $filter['by_val'] = '全部';
                break;
            default :
                //组织机构
                $parent_id = isset($data['parent_id'])?$data['parent_id']:0;
                $owner_uid = isset($data['owner_uid'])?$data['owner_uid']:'';
                if($parent_id!=0 || $owner_uid!=''){
                    if($parent_id!=0 && $owner_uid=='') {
                        //获取该部门的用户
                        $dep_ids = $sysUser->getUserListByDepartmentId($parent_id, 'key');
                        $dep_ids_str = implode(',', $dep_ids);
                        $where .= " and a.owner_uid in (" . $dep_ids_str . ")";
                        $page_info .="parent_id=".$parent_id."&";
                        $filter['parent_id'] = $parent_id;
                        $filter['by_val'] = '部门';
                    }
                    if($owner_uid!='') {
                        $where .= " and a.owner_uid =" . $owner_uid;
                        $page_info .="owner_uid=".$owner_uid."&";
                        $filter['owner_uid'] = $owner_uid;
                        $filter['by_val'] = '人员';
                    }
                }else{
                    $where .= " and a.owner_uid>0 ";
                    $filter['by_val'] = '全部';
                }
                break;
        }

        if($by!='resource'){
            if($this->baseCode->esf->is_out) {
                //$warn_outdate = time() - (86400 * $this->baseCode->esf->danger_outdays);
                //$where .= " and a.log_date>" . $warn_outdate;
            }
        }

        //是否有效
        $where .= ' and a.flag='.$flag.' ';
        $page_info .="flag=".$flag."&";
        $filter['flag'] = $flag;

        //城市
        $where .= " and a.city_code = '".$this->city_code."'";
        $page_info .="city_code=".$this->city_code."&";

        //创建者
        $create_uid = isset($data['create_uid'])?$data['create_uid']:0;
        if($create_uid != 0){
            $where .= " and a.create_uid = ".$create_uid;
            $filter['create_uid'] = $create_uid;
            $page_info .="create_uid=".$create_uid."&";
        }

        //开始时间
        $start_date = isset($data['start_date'])?$data['start_date']:0;
        if($start_date != 0){
            $where .= " and a.create_date >= ".$start_date;
            $filter['start_date'] = $start_date;
            $page_info .="start_date=".$start_date."&";
        }
        //结束时间
        $end_date = isset($data['end_date'])?$data['end_date']:0;
        if($end_date != 0){
            $where .= " and a.create_date <= ".$end_date;
            $filter['end_date'] = $end_date;
            $page_info .="end_date=".$end_date."&";
        }

        //房屋状态
        $status = isset($data['status'])?$data['status']:'1';
        if($status!='0'){
            if($status==1){
                $where .= " and (a.status = ".intval($status)." or a.status = 5) ";
            }else{
                $where .= " and a.status = ".intval($status);
            }
            $page_info .="status=".$status."&";
            $filter['status'] = $status;
            $filter['status_value'] = '不限';
        }else{
            $filter['status'] = $status;
            $filter['status_value'] = '状态';
        }

        //物业类型
        $pm_type = isset($data['pm_type'])?$data['pm_type']:'20306';
        if($pm_type!='0'){
            $where .= " and a.pm_type = ".intval($pm_type);
            $page_info .="pm_type=".$pm_type."&";
            $filter['pm_type'] = $pm_type;
            $filter['pm_type_value'] = '不限';
        }else{
            $filter['pm_type'] = $pm_type;
            $filter['pm_type_value'] = '用途';
        }

        //户型
        $shi = isset($data['shi'])?$data['shi']:'0';
        if($shi!= '0'){
            $where .= " and a.shi = ".intval($shi);
            $page_info .="shi=".$shi."&";
            $filter['shi'] = $shi;
            $filter['shi_value'] = '不限';
        }else{
            $filter['shi'] = $shi;
            $filter['shi_value'] = '户型';
        }

        //工位
        $work_station = isset($data['work_station'])?$data['work_station']:'0';
        if($work_station!= '0'){
            $_work_station = explode('-',$work_station);
            $where .= " and a.work_station >= ".intval($_work_station[0])." and a.work_station<=".intval($_work_station[1]);
            $page_info .="work_station=".$work_station."&";
            $filter['work_station'] = $work_station;
            $filter['work_station_value'] = '不限';
        }else{
            $filter['work_station'] = $work_station;
            $filter['work_station_value'] = '工位';
        }

        //行政区域
        $borough = isset($data['borough'])?$data['borough']:'0';
        if($borough != '0'){
            $where .= " and b.borough = ".intval($borough);
            $page_info .="borough=".$borough."&";
            $filter['borough'] = $borough;
            $filter['borough_value'] = '不限';
        }else{
            $filter['borough'] = $borough;
            $filter['borough_value'] = '区域';
        }

        //商圈
        $business_region = isset($data['business_region'])?$data['business_region']:'0';
        if($business_region != '0'){
            $where .= " and b.business_region = ".intval($business_region);
            $page_info .="business_region=".$business_region."&";
            $filter['business_region'] = $business_region;
            $filter['business_region_value'] = '不限';
        }else{
            $filter['business_region'] = $business_region;
            $filter['business_region_value'] = '商圈';
        }

        //面积
        $area = isset($data['area'])?$data['area']:'0';
        if($area != '0'){
            $_area = explode('-',$area);
            $where .= " and a.total_area >= ".intval($_area[0])." and a.total_area<=".intval($_area[1]);
            $page_info .="area=".$area."&";
            $filter['area'] = $area;
            if(isset($this->baseCode->area_option[$filter['area']])){
                $filter['area_value'] = $this->baseCode->area_option[$filter['area']];
            }else{
                if($_area[0]==0){
                    $filter['area_value'] = $_area[1].'m²以下';
                }elseif($_area[1]==0){
                    $filter['area_value'] = $_area[0].'m²以上';
                }else{
                    $filter['area_value'] = $filter['area'].'m²';
                }
            }
        }else{
            $filter['area'] = $area;
            $filter['area_value'] = '面积';
        }

        //价格
        $price = isset($data['price'])?$data['price']:'0';
        if($price != '0'){
            $_price = explode('-',$price);
            $where .= " and a.price >= ".intval($_price[0])." and a.price<=".intval($_price[1]);
            $page_info .="price=".$price."&";
            $filter['price'] = $price;
            if(isset($this->baseCode->price[$filter['price']])){
                $filter['price_value'] = $this->baseCode->price[$filter['price']];
            }else{
                if($_price[0]==0){
                    $filter['price_value'] = $_price[1].$price_unit.'以下';
                }elseif($_price[1]==0){
                    $filter['price_value'] = $_price[0].$price_unit.'以上';
                }else{
                    $filter['price_value'] = $filter['price'].$price_unit;
                }
            }
        }else{
            $filter['price'] = $price;
            $filter['price_value'] = '价格';
        }

        //朝向
        $toward = isset($data['toward'])?$data['toward']:'0';
        if($toward != '0'){
            $where .= " and a.toward = ".intval($toward);
            $page_info .="toward=".$toward."&";
            $filter['toward'] = $toward;
            $filter['toward_value'] = '不限';
        }else{
            $filter['toward'] = $toward;
            $filter['toward_value'] = '朝向';
        }

        //装修
        $fitment_type = isset($data['fitment_type'])?$data['fitment_type']:'0';
        if($fitment_type != '0'){
            $where .= " and a.fitment_type = ".intval($fitment_type);
            $page_info .="fitment_type=".$fitment_type."&";
            $filter['fitment_type'] = $fitment_type;
            $filter['fitment_type_value'] = '不限';
        }else{
            $filter['fitment_type'] = $fitment_type;
            $filter['fitment_type_value'] = '装修';
        }

        //更多
        $other = isset($data['other'])?$data['other']:'';
        foreach ($other as $ok=>$oi){
            if($oi=='haskey'){
                $data['haskey'] = 'haskey';
            }
            if($oi=='haspic'){
                $data['haspic'] = 'haspic';
            }
            if($oi=='hasvideo'){
                $data['hasvideo'] = 'hasvideo';
            }
        }
        //有钥匙
        $haskey = trim(isset($data['haskey'])?$data['haskey']:'');
        if($haskey!=''){
            $where .=" and a.look_way=22601";
            $page_info .="haskey=".$haskey."&";
            $filter['haskey'] = 'haskey';
        }else{
            $filter['haskey'] = $haskey;
        }
        //有图
        $haspic = trim(isset($data['haspic'])?$data['haspic']:'');
        if($haspic!=''){
            $where .=" and a.img_num>0";
            $page_info .="haspic=".$haspic."&";
            $filter['haspic'] = 'haspic';
        }else{
            $filter['haspic'] = $haspic;
        }
        //有视频
        $hasvideo = trim(isset($data['hasvideo'])?$data['hasvideo']:'');
        if($hasvideo!=''){
            $where .=" and a.video_num>0";
            $page_info .="hasvideo=".$hasvideo."&";
            $filter['hasvideo'] = 'hasvideo';
        }else{
            $filter['hasvideo'] = $hasvideo;
        }


        //栋号
        $build_no = trim(isset($data['build_no'])?$data['build_no']:'');
        if($build_no!=''){
            $where .= " and build_no = '" .$build_no . "'";
            $page_info .="build_no=".$build_no."&";
            $filter['build_no'] =$build_no;
        }else{
            $filter['build_no'] = $build_no;
        }
        //单元
        $unit_no = trim(isset($data['unit_no'])?$data['unit_no']:'');
        if($unit_no!=''){
            $where .= " and unit_no = '" .$unit_no . "'";
            $page_info .="unit_no=".$unit_no."&";
            $filter['unit_no'] =$unit_no;
        }else{
            $filter['unit_no'] = $unit_no;
        }
        //房号
        $house_no = trim(isset($data['house_no'])?$data['house_no']:'');
        if($house_no!=''){
            $where .= " and house_no like '%" .$house_no . "%'";
            $page_info .="house_no=".$house_no."&";
            $filter['house_no'] =$house_no;
        }else{
            $filter['house_no'] = $house_no;
        }

        //图片数量
        $img_num = trim(isset($data['img_num'])?$data['img_num']:0);
        if($img_num>0){
            //$where .= $this->analysisWhere($key);//高级搜索
            if($view=='file') {
                $where .= " and a.img_num >0";
                $page_info .= "img_num=" . $img_num . "&";
                $filter['img_num'] = $img_num;
            }
        }else{
            if($view=='file') { $filter['img_num'] = $img_num; }
        }

        //搜索小区
        $key = trim(isset($data['key'])?$data['key']:'');
        if($key!=''){
            //$where .= $this->analysisWhere($key);//高级搜索
            $where .= " and b.name like '%" . $key . "%'";
            $page_info .="key=".$key."&";
            $filter['key'] =$key;
        }else{
            $filter['key'] = $key;
        }

        //记录搜索结果
        $_SESSION['esf_referer'] = "/fc_esf/index?".$page_info;
        $select_columns = "select %s from fc_esf as a left join fc_project as b on a.project_id=b.id %s %s %s";
        $order = "order by $order";
        $limit = "limit $offset,$pageSize";
        $count = " count(a.id) as count ";
        $sql = sprintf($select_columns,'a.*,b.name as project_name',$where,$order,$limit);
        $sqlcount = sprintf($select_columns,$count,$where,'','');
        $res = $this->pdo->getAll($sql);

        $Count = $this->pdo->getRow($sqlcount);
        $recordCount = $Count['count'];
        $page=new Pager($pageSize,$recordCount,$currentPage,$subPages,$page_info,4);
        $splitPageStr=$page->get_page_html();

        foreach ($res as $key => $value) {
            //key
            $res[$key]['index'] = $key+1+$offset;

            //获取内部配套  todo 优化效率
            $res[$key]['facilities_val'] = $this->metaData->getNameByCode($value['facilities']);
            //装修
            $res[$key]['fitment_type_val'] = $this->fitment_type_option[$value['fitment_type']];
            //家具
            $res[$key]['furniture_val'] = $this->baseCode->furniture_option[$value['furniture']];
            //价格整数
            $res[$key]['price_int'] = number_format($value['price'],0);

            if(isset($value['log_date']) && $value['log_date']!=0){
                $res[$key]['log_date'] = Util::formatDate($value['log_date']);
                //$res[$key]['log_date2'] = date('Y-m-d H:i:s', $value['log_date']);
                $res[$key]['out_time'] = time()-$value['log_date'];
            }else{
                $res[$key]['log_date'] = '暂无';
                //$res[$key]['log_date2'] = '暂无';
                $res[$key]['out_time'] = time()-$res[$key]['create_date'];
            }
            $res[$key]['log_num'] = $this->getEsfFollowNum($value['id']);

            $res[$key]['toward_val']=$this->toward_option[$value['toward']];//朝向

            //房源状态
            $res[$key]['status_val'] = $this->baseCode->esf_status_option[$value['status']];
            $res[$key]['status_color'] = Util::statusColor($value['status']);

            //获取看房次数
            $res[$key]['visit_num'] = $this->getEsfVisitNum($value['id']);

            $res[$key]['create_date']=date('Y-m-d', $value['create_date']);
            //获取负责人
            $owner = $sysUser->getUserNameById($value['owner_uid']);
            $res[$key]['owner_name'] = $owner['true_name'];
            $res[$key]['huxing'] = $this->tranHuxing($value['ting'],$value['shi']);
            $res[$key]['address']= $this->tranAddress($value['build_no'],$value['unit_no']);
            //看房方式
            $res[$key]['look_way_val'] = $this->look_way_option[$value['look_way']];
            //房源等级
            $res[$key]['house_level_val'] = $this->house_level_option[$value['house_level']];

            //统计图片
            if($value['img_path']==''){
                $img = $this->getEsfPic($value['id'],0,1);
                if(count($img)>0)$res[$key]['img_path'] = str_replace('.','_s.',$img[0]['url']);
            }else{
                $res[$key]['img_path'] = str_replace('.','_s.',$value['img_path']);
            }
            //判断是否有视频

        }

        $result['list'] = $res;
        $result['cnt'] = $recordCount;
        $result['filter'] = $filter;
        $result['price_unit'] = $price_unit;
        $result['unit_price_unit'] = $unit_price_unit;
        $result['page_info'] = $page_info;
        $result['splitPageStr'] = $splitPageStr;
        $result['header'] = $header;
        $result['next_page'] = $currentPage+1;
        $result['hasmore'] = (($pageSize*$currentPage)<=$recordCount)?1:0;
        return $result;
    }

    /* 新增房源 */
    public function add($data,$user){
        $this->session = (object)$user;
        if(isset($data["cost_detail"]))$data["cost_detail"]=implode(',',$data["cost_detail"]);//费用明细
        if(isset($data["facilities"]))$data["facilities"]=implode(',',$data["facilities"]);//配套
        if(isset($data["sale_point"]))$data["sale_point"]=implode(',',$data["sale_point"]);//卖点
        if(isset($data["key_uid"]))$data["key_date"]=time();
        $data["mobile"] = preg_replace('# #','',$data['mobile']);
        $data["house_level"] = 24202;//新增房源等级默认为24202 B级
        $data["status"] = 1;//新增房源状态为1有限(5暂缓)
        $data['log_date'] = time();
        $data['create_uid'] = $this->session->user_id;
        $data['write_uid'] = $this->session->user_id;
        $data['owner_uid'] = $this->session->user_id;
        //if(isset($param['build_year']))$param['build_year']=strtotime($param['build_year']);//建筑年代

        //todo: 设置城市
        $data['city_code']=$this->session->city_code;

        if($data){
            $rlt = $this->pdo->add($data,'fc_esf');
            if($rlt){
                $sysLog = new SysLog();
                $sysLog->actionLog($rlt,$this->session->user_id,'新增房源','fc_esf','add');//系统日志

                $analytics = new Analytics();
                $analytics->updateKpiByType($this->session->user_id,'esf_num',date('Y'),intval(date('m')));

                $result['id'] = $rlt;
                $result['msg'] = '新增成功!';
            }else{
                $result['id'] = $rlt;
                $result['msg'] = '新增失败!';
            }

        }else {
            $result['id'] = 0;
            $result['msg'] = '非法数据!';
        }
        return $result;
    }

    /* 更新房源 */
    public function update($data,$user){
        $this->session = (object)$user;
        if(isset($data["cost_detail"]))$data["cost_detail"]=implode(',',$data["cost_detail"]);//费用明细
        if(isset($data["facilities"]))$data["facilities"]=implode(',',$data["facilities"]);//配套
        if(isset($data["sale_point"]))$data["sale_point"]=implode(',',$data["sale_point"]);//卖点
        //if(isset($data['build_year']))$data['build_year']=strtotime($data['build_year']);//建筑年代
        $data["mobile"] = preg_replace('# #','',$data['mobile']);
        $id = isset($data['esf_id'])?$data['esf_id']:0;

        $Info = $this->getEsfBaseInfo($id);

        //房源拥有者上级可以修改下级房源
        if($Info['owner_uid']!=$this->session->user_id) {
            //获取该房源拥有者上级
            $sysUser = new SysUser();
            $super = $sysUser->getSupUserInfoById($Info['owner_uid']);
            if($super['id']==$this->session->user_id)$this->is_esf_owner_super = 1;
        }

        //处理钥匙所有者,如果钥匙所有者发送变化,记录变化时间
        if($Info['key_uid']!=$data['key_uid']){
            $data['key_date'] = time();
        }

        //禁止经纪人修改房源等级为A级
        if(strpos($this->session->role_name,'经纪人') !==false){
            if($Info['house_level']!=$data['house_level'] && $data['house_level']==24201){
                unset($data['house_level']);
            }
        }

        if($id>0){
            $logInfo = '修改房源';
            //判断是否修改过价格、或面积
            if($Info['price']!=$data['price']){
                $price_unit = ($Info['house_type']==1)?'元/月':'万元';
                $logInfo .= '<br>价格从<b class="text-danger"><i class="fa fa-yen"></i>'.$Info['price'].$price_unit.'</b>改为<b class="text-success"><i class="fa fa-yen"></i>'.$data['price'].$price_unit.'</b>';
            }

            //判断是否修改过联系方式
            if($Info['mobile']!=$data['mobile']){
                $logInfo .= '|<b class="text-danger">业主联系方式变动,从'.$Info['mobile'].'变为'.substr($data['mobile'],0,3).'********</b>';
            }
            //判断是否修改过面积
            if($Info['total_area']!=$data['total_area']){
                $logInfo .= '|面积从<b class="text-danger">'.$Info['total_area'].'</b>m²,改为<b class="text-success">'.$data['total_area'].'m²</b>';
            }
            //项目是否修改
            if($Info['project_id']!=$data['project_id']){
                $logInfo .= '|项目从<b class="text-danger">'.$Info['project_name'].'</b>,改为<b class="text-success">'.$data['project_name'].'</b>';
            }
            //楼栋是否修改
            if($Info['build_no']!=$data['build_no']){
                $logInfo .= '|楼栋从<b class="text-danger">'.$Info['build_no'].'</b>,改为<b class="text-success">'.$data['build_no'].'</b>';
            }
            //单元是否修改
            if($Info['unit_no']!=$data['unit_no']){
                $logInfo .= '|单元从<b class="text-danger">'.$Info['unit_no'].'</b>,改为<b class="text-success">'.$data['unit_no'].'</b>';
            }
            //房号是否修改
            if($Info['house_no']!=$data['house_no']){
                $logInfo .= '|房号从<b class="text-danger">'.$Info['house_no'].'</b>,改为<b class="text-success">'.$data['house_no'].'</b>';
            }
            //房源描述[内部]是否修改
            if($Info['desc']!=$data['desc']){
                $logInfo .= '|房源描述从<b class="text-danger">'.$Info['desc'].'</b>,改为<b class="text-success">'.$data['desc'].'</b>';
            }
            $sysLog = new SysLog();
            $sysLog->actionLog($id,$this->session->user_id,$logInfo,'fc_esf','update');

            //房源管理员可以修改所有楼盘信息
            if($this->session->user_type==4 || $this->is_esf_owner_super==1 || $this->session->user_type==1){
                $rlt = $this->pdo->update($data,'fc_esf','id='.$id.' ');
                //echo $this->pdo->getLastSql();exit;
            }else{
                $rlt = $this->pdo->update($data,'fc_esf','id='.$id.' and owner_uid='.$this->session->user_id);
            }
            $result['rlt'] = $rlt;
            $result['id'] = $id;
            if($rlt){
                //钥匙持有者kpi
                if($data['old_key_uid']!=$data['key_uid'] && $data['key_uid']!=0){
                    $analytics = new Analytics();
                    $analytics->updateKpiByType($data['key_uid'],'key_num',date('Y'),intval(date('m')));
                }
                $result['msg'] = '修改成功!';
            }else{
                $result['msg'] = '修改失败!';
            }
        }else{
            $result['rlt'] = 0;
            $result['msg'] = '非法房源数据!';
        }
        return $result;
    }

    /* 获取房源基本信息 */
    public function getEsfBaseInfo($esf_id){
        $sql = "select a.id,a.create_uid,a.write_uid,a.owner_uid,a.house_type,a.project_id,a.status,a.total_area,a.house_no,a.build_no,a.unit_no,a.price,a.unit_price,a.total_area,a.mobile,a.desc,b.name as project_name from fc_esf as a left join fc_project as b on a.project_id=b.id where a.id=".$esf_id;
        //初始数据
        $Info = $this->pdo->getRow($sql);
        $Info['address']= $this->tranAddress($Info['build_no'],$Info['unit_no']);
        return $Info;
    }

    /* 获取房源详情 */
    public function getEsfInfo($esf_id){
        $sql = "select a.*,
                b.name as project_name,b.address,b.borough,b.region,b.business_region,b.build_num,b.family_num,b.pm_type as project_pm_type,
                b.pm_level as project_pm_level,b.manage_price,b.manage_company,b.manage_telephone,b.developer,b.build_year,b.city_code,
                b.total_area as project_total_area,b.greenbelt,b.cubage,b.parking_num,b.business_area,b.height_floor,
                b.office_area,b.tier_area,b.total_occupy,b.des,
                b.map_x,b.map_y from fc_esf as a left join fc_project as b on a.project_id=b.id where a.id=".$esf_id;
        $sql = "select a.*,
                b.name as project_name,b.address,b.borough,b.region,b.business_region,b.pm_type as project_pm_type,
                b.developer,b.build_year,b.city_code,
                b.total_area as project_total_area,b.greenbelt,b.cubage,b.business_area,b.office_area,b.total_occupy,b.des,
                b.map_x,b.map_y from fc_esf as a left join fc_project as b on a.project_id=b.id where a.id=".$esf_id;
        //初始数据
        $Info = $this->pdo->getRow($sql);
        //跟进时间
        if(isset($Info['log_date']) && $Info['log_date']!=0){
            $Info['out_time'] = time()-$Info['log_date'];
        }else{
            $Info['out_time'] = time()-$Info['create_date'];
        }
        $Info['create_date'] = date('Y-m-d H:i',$Info['create_date']);
        $Info['cost_detail'] = explode(",", $Info['cost_detail']);
        $Info['facilities'] = explode(",", $Info['facilities']);
        $Info['scr_mobile'] = substr($Info['mobile'],0,3)."********";
        $Info['img_path'] = str_replace('.','_s.',$Info['img_path']);
        $Info['borough_val'] = $this->borough_option[$Info['borough']];
        $Info['address_sim']= $Info['borough_val'].'-'.$Info['address'];
        $Info['address_all']= $Info['borough_val'].'-'.$Info['address'].'-'.$this->tranAddress($Info['build_no'],$Info['unit_no']);
        $Info['address_no']= $this->tranAddress($Info['build_no'],$Info['unit_no'],$Info['house_no']);
        $Info['address_no_src']= $this->tranAddress($Info['build_no'],$Info['unit_no'],'****');
        $Info['fitment_type_val'] = $this->fitment_type_option[$Info['fitment_type']];//装修
        $Info['rent_payment_val'] = $this->baseCode->pay_way_option[$Info['rent_payment']];//付款方式
        $Info['pm_child_type_val'] = $this->baseCode->pm_type_child_option[$Info['pm_type']][$Info['pm_child_type']];//子物业类型
        $Info['pm_level_val']=$this->pm_level_option[$Info['pm_level']];//物业等级
        $Info['toward_val']=$this->toward_option[$Info['toward']];//朝向
        $Info['time_limit_val'] = $this->baseCode->time_limit_option[$Info['time_limit']];//最小租期
        $Info['furniture_val'] = $this->baseCode->furniture_option[$Info['furniture']];   //家具
        $Info['property_nature_val'] = $this->property_nature_option[$Info['property_nature']];//产权性质
        $Info['is_regist_company_val'] = $this->baseCode->boole_option[$Info['is_regist_company']];//是否可注册公司
        $Info['build_year_val'] = $this->build_year_option[$Info['build_year']];//建筑年代
        $Info['origin_val'] = $this->origin_option[$Info['origin']];//房源来源
        $Info['house_status_val'] = $this->house_status_option[$Info['house_status']];//房源现状
        $Info['property_status_val'] = $this->property_status_option[$Info['property_status']];//房源产权状态

        $Info['price'] = round($Info['price']);
        $Info['total_area'] = round($Info['total_area']).'m²';

        //看房方式
        $Info['look_way_val'] = $this->look_way_option[$Info['look_way']];
        //房源等级
        $Info['house_level_val'] = $this->house_level_option[$Info['house_level']];

        //楼盘信息
        $Info['region_val'] = $this->metaData->getNameByCode($Info['region']);
        $Info['business_region_val'] = $this->metaData->getNameByCode($Info['business_region']);
        $Info['project_pm_type_val'] = $this->metaData->getNameByCode($Info['project_pm_type']);
        $Info['project_pm_level_val'] = $this->pm_level_option[$Info['project_pm_level']];

        $sysUser = new SysUser();
        //首录人
        $Info['creater'] = $sysUser->getUserNameById($Info['create_uid']);
        //负责人
        $Info['owner'] = $sysUser->getUserNameById($Info['owner_uid'],'id,true_name,mobile');
        if($Info['key_uid']>0) {
            //钥匙人
            $keyer = $sysUser->getUserNameById($Info['key_uid']);
            $Info['key_name'] = $keyer['true_name'];
        }
        //房源状态
        $Info['status_val'] = $this->baseCode->esf_status_option[$Info['status']];
        $Info['status_color'] = Util::statusColor($Info['status']);

        //获取房源图片
        $Info['pics'] = $this->getEsfPic($esf_id,0,5,array('type'=>'img'));
        //获取房源视频
        if($Info['video_num']>0) {
            $Info['video'] = $this->getEsfPic($esf_id, 0, 1, array('type' => 'video'));
            $Info['video'] = $Info['video'][0];
        }

        //处理物业类型
        switch ($Info['pm_type']){
            case '20306':
                $this->facilities_option      = $this->metaData->getPairBaseCodeByType(232);
                break;
            default:
                $this->facilities_option      = $this->metaData->getPairBaseCodeByType(217);
                break;
        }
        foreach ($Info['facilities'] as $val){
            $Info['facilities_val'] .=$this->facilities_option[$val].'、';
        }

        //更新房源浏览量
        $this->hitNum($esf_id);

        if($Info['house_type']==1){
            $Info['price_unit'] = "元/月";
            $Info['unit_price_unit'] = '元/m²·月';
            $Info['house_type_val'] = '出租';
            $Info['price_lable'] = '租金';
        }else{
            $Info['price_unit'] = "万元";
            $Info['unit_price_unit'] = '元/m²';
            $Info['house_type_val'] = '出租';
            $Info['price_lable'] = '总价';
        }
        return $Info;
    }

    /* 获取房源相册视频 */
    public function getEsfPic($esf_id,$start=0,$num=100,$data=array(),$order='p.id desc'){
        $where = 'where p.esf_id='.$esf_id;
        //图片类型
        $code = isset($data['code'])?$data['code']:0;
        if($code) {
            $where .= " and p.code={$code}";
        }
        //文件类型
        $type = isset($data['type'])?$data['type']:'';
        switch ($type){
            case 'img':
                $where .= " and a.type<>'mp4'";
                break;
            case 'video':
                $where .= " and a.type='mp4'";
                break;
            default:
                break;
        }

        //$sql = "select p.id,p.code,p.esf_id,p.attach_id,a.type,p.title,p.des,p.is_show,a.url,a.type as file_type from fc_esf_pic as p left join fc_esf_attach as a on p.attach_id=a.id where flag=1 and p.esf_id={$esf_id} order by a.id desc limit 0,{$num}";
       $sql = "select p.id,p.create_date,p.code,p.esf_id,p.attach_id,p.title,p.des,p.is_show,a.url,u.true_name,a.type from fc_esf_pic as p left join fc_esf_attach as a on p.attach_id=a.id left join sys_user as u on p.create_uid=u.id {$where} and p.flag=1 ORDER BY {$order} limit {$start},{$num}";
        $res = $this->pdo->getAll($sql);
        foreach ($res as $key=>$item){
            if($item['type']=='mp4'){
                $res[$key]['file_type'] = 'video';
            }else {
                $res[$key]['file_type'] = 'img';
                $res[$key]['url_m'] = str_replace('.','_m.',$item['url']);
                $res[$key]['url_s'] = str_replace('.','_s.',$item['url']);
            }
        }
        return $res;
    }

    /* 获取房源看房客户记录 */
    public function getEsfVisit($data,$user){
        $this->session = (object)$user;
        $id = trim(isset($data["esf_id"])?$data["esf_id"]:0);
        $by = trim(isset($data["by"])?$data["by"]:'all');
        $house_type = intval(isset($data["house_type"])?$data["house_type"]:1);
        $page_info = "id=".$id."&house_type=".$house_type."&";
        $orderField = isset($data['sort']) ? $data['sort'] : 'a.id';
        $orderValue = isset($data['flag']) ? $data['flag'] : 'desc';

        $pageSize = 10;
        $offset = 0;
        $subPages=5;//每次显示的页数
        $currentPage = isset($data['page']) ? (int)$data['page'] : 0;
        if($currentPage>0) $offset=($currentPage-1)*$pageSize;
        $where = "where a.flag=1 and a.type='fc_esf' and a.action_id=".$id.' ';

        switch ($by) {
            //case 'today' : $where .= ' create_date='.strtotime(date('Y-m-d', time())) ; break;
            //case 'week' : $where['create_time'] =  array('gt',(strtotime(date('Y-m-d')) - (date('N', time()) - 1) * 86400)); break;
            //case 'month' : $where['create_time'] = array('gt',strtotime(date('Y-m-01', time()))); break;
            //case 'add' : $order = 'create_time desc'; break;
            //case 'update' : $order = 'update_time desc'; break;
            //case 'sub' : $where['owner_role_id'] = array('in',implode(',', $below_ids)); break;
            //case 'deleted' : $where['is_deleted'] = 1;break;
            case 'me' :
                $where .= "and a.create_uid=".$this->session->user_id." ";
                $page_info .= "by=".$by."&";
                break;
            //case 'focus' : $where['customer_id'] = array('in',$focus_id);break;
            //case 'share' : $where['customer_id'] = array('in',$customerid);break;
            //case 'myshare' : $where['customer_id'] = array('in',$share_customer_ids);break;
            default :
                break;
        }

        $select_columns = "select %s from crm_visit as a LEFT JOIN sys_user as b on a.create_uid=b.id %s %s %s";
        $select_cnt = "select %s from crm_visit as a %s %s %s";
        $order = "order by $orderField $orderValue";
        $limit = "limit $offset,$pageSize";
        $count = " count(a.id) as count ";
        $sql = sprintf($select_columns,'a.*,b.user_name,b.true_name,b.headimgurl',$where,$order,$limit);
        $sqlcount = sprintf($select_cnt, $count,$where,'','');
        $res = $this->pdo->getAll($sql);
        $Count = $this->pdo->getRow($sqlcount);
        $recordCount = $Count['count'];
        $page=new Pager($pageSize,$recordCount,$currentPage,$subPages,$page_info,4);
        $splitPageStr=$page->get_page_html();

        //关联客户信息
        $customer = new Customer();
        $sysUser = new SysUser();
        foreach ($res as $key=>$item){
            $res[$key]['customer'] = $customer->getCustomerInfoById($item['customer_id']);
            //陪看人员
            if($item['together_uid']!='') {
                $_together_uid = explode(',',$item['together_uid']);
                foreach ($_together_uid as $val) {
                    if($val!='') {
                        $together = $sysUser->getUserNameById($val);
                        $res[$key]['together_name'] .= $together['true_name'] . ',';
                    }
                }
            }else{
                $res[$key]['together_name'] = '无';
            }

            $res[$key]['visit_date_val'] = date('Y-m-d H:i',$item['visit_date']);

        }

        $result['list'] = $res;
        $result['pageStr'] = $splitPageStr;

        return $result;
    }

    /* 获取抢盘记录 */
    public function getEsfTask($data){
        $data['action_id'] = trim(isset($data["esf_id"])?$data["esf_id"]:0);
        $data['status'] = trim(isset($data["status"])?$data["status"]:'s1');
        $data['subtype'] = trim(isset($data["subtype"])?$data["subtype"]:'24105');
        //print_r($data);exit;
        $task = new Task();
        $res = $task->search($data);
        return $res;
    }

    /* 获取房源跟进日志 */
    public function getEsfFollow($data,$user){
        $this->session = (object)$user;
        $id = intval(isset($data["esf_id"])?$data["esf_id"]:0);
        $by = trim(isset($data["by"])?$data["by"]:'all');
        //$house_type = intval(isset($data["house_type"])?$data["house_type"]:1);
        //$page_info = "id=".$id."&house_type=".$house_type."&";
        $orderField = isset($data['sort']) ? $data['sort'] : 'a.id';
        $orderValue = isset($data['flag']) ? $data['flag'] : 'desc';

        $pageSize = 10;
        $offset = 0;
        $subPages=5;//每次显示的页数
        $currentPage = isset($data['page']) ? (int)$data['page'] : 0;
        if($currentPage>0) $offset=($currentPage-1)*$pageSize;
        $where = 'where b.flag=1 and a.esf_id='.$id.' ';

        $filter = array();//筛选条件
        $filter['id'] = $id;
        $filter['by'] = $by;
        $filter['sort'] = $orderField;
        $filter['sort_value'] = $orderValue;
        $page_info = "id=".$id."&";

        switch ($by) {
            case 'me' :
                $where .= "and b.create_uid=".$this->session->user_id." ";
                $page_info .= "by=".$by."&";
                break;
            default :
                break;
        }

        //主题
        $subject = isset($data['subject'])?$data['subject']:'';
        if($subject != ''){
            $where .= " and b.subject = '".$subject."'";
            $filter['subject'] = $subject;
            $page_info .="subject=".$subject."&";
        }

        $select_columns = "select %s from crm_r_esf_log as a LEFT JOIN crm_log as b on a.log_id=b.id %s %s %s";
        $order = "order by $orderField $orderValue";
        $limit = "limit $offset,$pageSize";
        $count = " count(a.id) as count ";
        $sql = sprintf($select_columns,'b.*',$where,$order,$limit);
        $sqlcount = sprintf($select_columns, $count,$where,'','');
        $res = $this->pdo->getAll($sql);
        $Count = $this->pdo->getRow($sqlcount);
        $recordCount = $Count['count'];
        $page=new Pager($pageSize,$recordCount,$currentPage,$subPages,$page_info,4);
        $splitPageStr=$page->get_page_html();

        //关联用户信息
        $sysUser = new SysUser();
        foreach ($res as $key=>$item){
            $res[$key]['user'] = $sysUser->getUserInfoById($item['create_uid']);
            $res[$key]['create_date'] = Util::formatDate($item['create_date']);
        }
        $result['list'] = $res;
        $result['pageStr'] = $splitPageStr;
        $result['cnt'] = $recordCount;
        $result['next_page'] = $currentPage+1;
        $result['sql'] = $sql;
        $result['hasmore'] = (($pageSize*$currentPage)<=$recordCount)?1:0;

        return $result;
    }

    /* 获取房源管理者对房源的跟进日志 */
    public function getSelfEsfFollowById($id,$start=0,$limit=1){
        $orderField = isset($data['sort']) ? $data['sort'] : 'a.id';
        $orderValue = isset($data['flag']) ? $data['flag'] : 'desc';
        $where = "where b.flag=1 and a.esf_id={$id}";
        $select_columns = "select %s from crm_r_esf_log as a LEFT JOIN crm_log as b on a.log_id=b.id %s %s %s";
        $order = "order by $orderField $orderValue";
        $limit = "limit $start,$limit";
        $sql = sprintf($select_columns,'b.*',$where,$order,$limit);
        $res = $this->pdo->getAll($sql);
        //关联用户信息
        $sysUser = new SysUser();
        foreach ($res as $key=>$item){
            $res[$key]['user'] = $sysUser->getUserInfoById($item['create_uid']);
        }
        return $res;
    }

    /* 获取最近需要填写跟进记录 */
    public function getNeedEsfFollow($user){
        //$sql = "select * from sys_action_log where module='fc_esf' and (action='showtel' or action='showhouseno') and status=0 and create_uid=".$user['user_id'];
        $sql = "select * from sys_action_log where module='fc_esf' and action='showtel' and status=0 and create_uid=".$user['user_id'];
        $rlt = $this->pdo->getRow($sql);
        return $rlt;
    }

    /* 判断是否有需要填写的跟进记录 */
    public function isNeedEsfFollow($user){
        $sql = "select count(*) as cnt from sys_action_log where module='fc_esf' and action='showtel' and status=0 and create_uid=".$user['user_id'];
        $rlt = $this->pdo->getRow($sql);
        return $rlt['cnt'];
    }

    /* 获取房源跟进数量 */
    public function getEsfFollowNum($id){
        $sql = "select count(*) as cnt from crm_r_esf_log where esf_id={$id}";
        $res = $this->pdo->getRow($sql);
        return $res['cnt'];
    }

    /* 获取房源看房数量 */
    public function getEsfVisitNum($id){
        $sql = "select count(*) as cnt from crm_visit where action_id={$id} and type='fc_esf'";
        $res = $this->pdo->getRow($sql);
        return $res['cnt'];
    }

    /* 更新浏览量 */
    public function hitNum($id){
        $rlt = $this->pdo->doSql("update fc_esf set hits_num=hits_num+1 where id={$id}");
        return $rlt;
    }

    /* 更新图片量 */
    public function updatePicNum($id){
        //直接统计图片的数量,进行更新
        $sql = "select count(*) as cnt from fc_esf_pic where esf_id={$id} and flag=1";
        $total_num = $this->pdo->getRow($sql);
        $sql = "select count(*) as cnt from fc_esf_pic where esf_id={$id} and flag=1 and code=21001";
        $diagram_cnt = $this->pdo->getRow($sql);
        $diagram_num = $diagram_cnt['cnt'];
        $img_num = $total_num['cnt'];
        $sql = "update fc_esf set img_num={$img_num}, img_diagram_num={$diagram_num} where id={$id}";
        $rlt = $this->pdo->doSql($sql);
        return $rlt;
    }

    /* 更新视频量 */
    public function updateVideoNum($id,$type='mp4'){
        //直接统计图片的数量,进行更新
        $sql = "select count(a.id) as cnt from fc_esf_pic as p left join fc_esf_attach as a on p.attach_id=a.id where p.esf_id={$id} and p.flag=1 and a.type='{$type}'";
        $total_num = $this->pdo->getRow($sql);
        $video_num = $total_num['cnt'];
        $sql = "update fc_esf set video_num={$video_num} where id={$id}";
        $rlt = $this->pdo->doSql($sql);
        return $rlt;
    }

    /* 返回户型图数量 */
    public function diagramImgNum($id){
        $sql = "select count(*) as cnt from fc_esf_pic where esf_id={$id} and flag=1 and code=21001";
        $diagram_cnt = $this->pdo->getRow($sql);
        $diagram_num = $diagram_cnt['cnt'];
        return $diagram_num;
    }

    /* 返回所有图数量 */
    public function imgNum($id){
        $sql = "select count(*) as cnt from fc_esf_pic where esf_id={$id} and flag=1";
        $img_cnt = $this->pdo->getRow($sql);
        $img_num = $img_cnt['cnt'];
        return $img_num;
    }

    /* 自动更新房源状态 */
    public function updateEsfStatusByAuto($esf_id){
        //更新房源状态,有2种情况
        //1、房源状态为5暂缓时,户型图片大于1,且房源图片大于7的情况下,把房源状态改为有效
        //2、房源状态为1有效时,删除了户型图片,或者房源图片小于7的情况下,把房源状态改为暂缓
        $img_num = $this->imgNum($esf_id);
        $diagram_num = $this->diagramImgNum($esf_id);
        $status = $this->getEsfStatus($esf_id);
        if($status==5 && $img_num>=$this->baseCode->esf->img_num && $diagram_num>0){
            $rlt = $this->updateEsfStatus($esf_id,1);
        }
        if($status==1 && ($img_num<$this->baseCode->esf->img_num || $diagram_num==0)){
            //房源状态为1有效时,删除了户型图片,或者房源图片小于7的情况下,把房源状态改为暂缓
            //$rlt = $this->updateEsfStatus($esf_id,5);
        }
    }

    /* 更新房源状态 */
    public function updateEsfStatus($esf_id,$status){
        $sql = "update fc_esf set status={$status} where id={$esf_id}";
        $rlt = $this->pdo->doSql($sql);
        return $rlt;
    }

    /* 获取房源状态 */
    public function getEsfStatus($esf_id){
        $sql = "select a.status from fc_esf as a where a.id=".$esf_id;
        //初始数据
        $Info = $this->pdo->getRow($sql);
        return $Info['status'];
    }

    /* 获取房源来源 */
    public function getOriginById($esf_id){
        $sql = "select a.origin from fc_esf as a where a.id={$esf_id}";
        $Info = $this->pdo->getRow($sql);
        if(!empty($Info['origin'])){
            return $this->origin_option[$Info['origin']];
        }else{
            return false;
        }
    }

    /* 更新房源等级 */
    public function updateEsfLevel($esf_id,$level){
        $sql = "update fc_esf set house_level={$level} where id={$esf_id}";
        $rlt = $this->pdo->doSql($sql);
        return $rlt;
    }

    /* 转入、出房源池 */
    public function updateEsfPond($esf_id){
        $sql = "update fc_esf set owner_uid=0 where id={$esf_id}";
        $rlt = $this->pdo->doSql($sql);
        return $rlt;
    }

    /* 获取房源池房源 */
    public function getEsf($esf_id){
        $Info = $this->getEsfBaseInfo($esf_id);

        $isOut = $this->isOutdate($Info['log_date'],'danger');
        //只有房源池中房源,才可以被获取
        if($Info['owner_uid']==0 || $isOut){
            $sql = "update fc_esf set owner_uid=" . $this->session->user_id . ",log_date=".time()." where id={$esf_id}";
            $rlt = $this->pdo->doSql($sql);
            if ($rlt) {
                return true;
            } else {
                return false;
            }
        }else{
            return false;
        }
    }

    /* 是否为房源池房源 */
    public function isOutdate($curDate,$type='warn'){
        //如果为客户池客户
        if($type=='warn') {
            $warn_outdate = time() - (86400 * $this->baseCode->esf->warn_outdays);
            $is_out = ($curDate < $warn_outdate) ? 1 : 0;
        }else{
            $danger_outdate = time()-(86400*$this->baseCode->esf->danger_outdays);
            $is_out = ($curDate < $danger_outdate) ? 1 : 0;
        }
        return $is_out;
    }

    /* 获取用户的房源列表 */
    public function getEsfListByUserId($user_id,$currentPage=0){
        $pageSize = 30;
        $offset = 0;
        if($currentPage>0) $offset=($currentPage-1)*$pageSize;
        $order = "order by a.create_date desc ";
        $limit = "limit {$offset},{$pageSize}";
        $sql = "select a.*,b.name as project_name,b.borough as p_borough,b.address as p_address from fc_esf as a left join fc_project as b on a.project_id=b.id 
                where a.owner_uid = {$user_id} and a.flag=1 ".$order." ".$limit;
        $sqlcnt = "select count(*) as cnt from fc_esf where owner_uid = {$user_id} and flag=1";
        $rlt = $this->pdo->getAll($sql);
        foreach ($rlt as $key=>$Info){
            $rlt[$key]['address_sim']= $this->borough_option[$Info['p_borough']].'-'.$Info['p_address'];
            $rlt[$key]['address_all']= $this->borough_option[$Info['p_borough']].'-'.$Info['p_address'].'-'.$this->tranAddress($Info['build_no'],$Info['unit_no'],$Info['house_no']);

            $rlt[$key]['house_type_val'] = '出售';
            if ($Info['house_type'] == 1) {
                $rlt[$key]['house_type_val'] = "出租";
            }

            //房源状态
            $rlt[$key]['status_val'] = '<span class="'.Util::statusColor($Info['status'],'badge').'">'.$this->baseCode->esf_status_option[$Info['status']].'</span>';

            $rlt[$key]['create_date_val'] = date('Y-m-d H:i',$Info['create_date']);
        }
        $data['list'] = $rlt;
        $cnt = $this->pdo->getRow($sqlcnt);
        $data['cnt'] = $cnt['cnt'];
        $data['page'] = $currentPage;
        return $data;
    }

    /* 获取推荐楼盘 */
    public function getRecommend($is_recommend=1,$limit=3,$order='order by a.id desc'){
        $sql = "select a.id,a.price,a.total_area,a.fitment_type,a.img_path,b.name as project_name,b.address,b.borough,b.img_url  
                from fc_esf as a LEFT JOIN fc_project as b on a.project_id=b.id 
                where a.flag=1 and a.is_recommend={$is_recommend} {$order} limit 0,{$limit}";
        $rlt = $this->pdo->getAll($sql);
        foreach($rlt as $key=>$item){
            $rlt[$key]['fitment_type_val'] = $this->fitment_type_option[$item['fitment_type']];//装修
            $rlt[$key]['price'] = round($item['price']);
            $rlt[$key]['total_area'] = round($item['total_area']);
            $rlt[$key]['unit_price'] = round($item['price']/$item['total_area']);
            $rlt[$key]['address_sim']= $this->borough_option[$item['borough']].'-'.$item['address'];
        }
        return $rlt;
    }

    /* 更新房源推荐 */
    public function updateEsfRecommend($esf_id,$is_recommend){
        $sql = "update fc_esf set is_recommend={$is_recommend} where id={$esf_id}";
        $rlt = $this->pdo->doSql($sql);
        return $rlt;
    }

    /* 验证房源是否存在 */
    public function checkHouseExist($project_id,$build_no,$unit_no,$house_no,$house_type){
        $sql = "select count(id) as cnt from fc_esf where project_id={$project_id} and build_no='{$build_no}' and unit_no='{$unit_no}' and house_no='{$house_no}' and house_type={$house_type}";
        $cnt = $this->pdo->getRow($sql);
        if($cnt['cnt']>0) {
            $data = array('success' => false, 'des' => '该房源已经存在');
        }else{
            $data = array('success' => true, 'des' => '验证通过');
        }
        return $data;
    }

    /* 转交记录 */
    public function recordList($data){
        $where = " 1=1 ";
        //拥有者
        $owner_uid = isset($data['owner_uid'])?$data['owner_uid']:0;
        if($owner_uid != 0){
            $where .= " and a.owner_uid = ".intval($owner_uid);
        }
        //开始时间
        $start_date = isset($data['start_date'])?$data['start_date']:0;
        if($start_date != 0){
            $where .= " and a.create_date >= ".$start_date;
        }
        //结束时间
        $end_date = isset($data['end_date'])?$data['end_date']:0;
        if($end_date != 0){
            $where .= " and a.create_date <= ".$end_date;
        }
        $sql = "SELECT * FROM fc_esf_record as a  WHERE ".$where;
        $rlt = $this->pdo->getAll($sql);

        $sysUser = new SysUser();
        foreach ($rlt as $key=>$val){
            $esfInfo = $this->getEsfBaseInfo($val['esf_id']);
            $rlt[$key]['create_date_val'] = date('Y-m-d H:i',$val['create_date']);
            $rlt[$key]['name'] = $esfInfo['project_name'];
            $rlt[$key]['address'] = $this->tranAddress($esfInfo['build_no'],$esfInfo['unit_no'],$esfInfo['house_no']);
            //转交人
            $rlt[$key]['creater'] = $sysUser->getUserNameById($val['create_uid']);
            //获得者
            $rlt[$key]['owner'] = $sysUser->getUserNameById($val['owner_uid']);
            $rlt[$key]['url'] = '/fc_esf/show?id='.$val['esf_id'];
        }

        return $rlt;
    }

    /* 价格(议价)记录 */
    public function getEsfPrice($data){
        $orderField = isset($data['sort']) ? $data['sort'] : 'a.id';
        $orderValue = isset($data['flag']) ? $data['flag'] : 'desc';

        $pageSize = 10;
        $offset = 0;
        $subPages=5;//每次显示的页数
        $currentPage = isset($data['page']) ? (int)$data['page'] : 0;
        if($currentPage>0) $offset=($currentPage-1)*$pageSize;
        $where = 'where a.flag=1 ';

        $filter = array();//筛选条件
        $filter['sort'] = $orderField;
        $filter['sort_value'] = $orderValue;
        $page_info = "";
        //房源
        $esf_id = isset($data['esf_id'])?$data['esf_id']:0;
        if($esf_id != 0){
            $where .= " and a.esf_id = ".intval($esf_id);
            $filter['esf_id'] = $esf_id;
            $page_info .="esf_id=".$esf_id."&";
        }
        //状态
        $status = isset($data['status'])?$data['status']:0;
        if($status=='all'){
            $where .= " and a.status < 9 ";
        }else {
            $where .= " and a.status = ".intval($status);
        }
        $filter['status'] = $status;
        $page_info .="status=".$status."&";

        $select_columns = "select %s from fc_esf_price as a %s %s %s";
        $order = "order by $orderField $orderValue";
        $limit = "limit $offset,$pageSize";
        $count = " count(a.id) as count ";
        $sql = sprintf($select_columns,'a.*',$where,$order,$limit);
        $sqlcount = sprintf($select_columns, $count,$where,'','');
        $res = $this->pdo->getAll($sql);
        $Count = $this->pdo->getRow($sqlcount);
        $recordCount = $Count['count'];
        $page=new Pager($pageSize,$recordCount,$currentPage,$subPages,$page_info,4);
        $splitPageStr=$page->get_page_html();

        //获取当前房源价格
        $esfInfo = $this->getEsfBaseInfo($esf_id);
        if($esfInfo['house_type']==1){
            $price_unit = '元/月';
            $unit_price_unit = '元/m²·月';
            $price_lable = '租金';
        }else{
            $price_unit = '万';
            $unit_price_unit = '元/m²';
            $price_lable = '总价';
        }

        //关联用户信息
        $sysUser = new SysUser();
        foreach ($res as $key=>$item){
            //创建者
            $create_user = $sysUser->getUserNameById($item['create_uid']);
            $res[$key]['create_name'] = $create_user['true_name'];

            $res[$key]['user'] = $sysUser->getUserInfoById($item['create_uid']);
            $res[$key]['create_date'] = Util::formatDate($item['create_date']);
            $res[$key]['cur_price'] = $esfInfo['price'];
            $res[$key]['cur_unit_price'] = $esfInfo['unit_price'];
            //计算价格浮动
            $res[$key]['float_price'] = $item['price']-$esfInfo['price'];
            $res[$key]['float_per'] = number_format(($res[$key]['float_price']/$esfInfo['price'])*100,2);
            $res[$key]['cur_float_price'] = number_format($res[$key]['float_price']/$esfInfo['total_area'],2);
            if($esfInfo['house_type']==1){
                $res[$key]['unit_price'] = number_format($item['price']/$esfInfo['total_area'],2);
            }else{
                $res[$key]['unit_price'] = number_format(($item['price']*10000)/$esfInfo['total_area'],2);
            }
            if($esfInfo['price']>$item['price']){
                $res[$key]['float_val'] = '下浮';
                $res[$key]['float_color'] = 'green';
                $res[$key]['float_icon'] = 'icon_trigondown_green.png';
            }elseif($esfInfo['price']<$item['price']){
                $res[$key]['float_val'] = '上浮';
                $res[$key]['float_color'] = 'red';
                $res[$key]['float_icon'] = 'icon_trigonup_red.png';
            }else{
                $res[$key]['float_val'] = '浮动';
                $res[$key]['float_color'] = 'gray-dark';
                $res[$key]['float_icon'] = 'icon_trigonright_gray.png';
            }
        }

        $result['price_unit'] = $price_unit;
        $result['unit_price_unit'] = $unit_price_unit;
        $result['price_lable'] = $price_lable;

        $result['list'] = $res;
        $result['pageStr'] = $splitPageStr;
        $result['cnt'] = $recordCount;
        $result['next_page'] = $currentPage+1;
        //$result['sql'] = $sql;
        $result['hasmore'] = (($pageSize*$currentPage)<=$recordCount)?1:0;

        return $result;
    }

    /* 户型转换 */
    public function tranHuxing($ting='',$shi=''){
        $shiStr = '';
        $tingStr = '';
        switch($shi){
            case '0':
                $shiStr ='';
                break;
            case '1':
                $shiStr ='一室';
                break;
            case '2':
                $shiStr ='二室';
                break;
            case '3':
                $shiStr ='三室';
                break;
            case '4':
                $shiStr ='四室';
                break;
            case '5':
                $shiStr ='五室以上';
                break;
            default:
                $shiStr ='五室以上';
                break;
        }
        switch($ting){
            case '0':
                $shiStr ='';
                break;
            case '1':
                $tingStr = '一厅';
                break;
            case '2':
                $tingStr = '二厅';
                break;
            case '3':
                $tingStr = '三厅';
                break;
            case '4':
                $tingStr = '四厅';
                break;
            default:
                $tingStr = '四厅以上';
                break;
        }
        $huxing = $shiStr.$tingStr;
        return $huxing;
    }

    /* 地址转换 */
    public function tranAddress($build_no='',$unit_no='',$house_no='',$unit='栋'){
        $address = $build_no.$unit.$unit_no.'单元';
        if($house_no!='')$address.=$house_no.'号';
        return $address;
    }

    /* 区域转换 */
    public function tranRegion($borough,$region){
        $codeName = $this->baseCode->getNameByCode($region);
        $region = $this->borough_option[$borough].'-'.$codeName;
        return $region;
    }

    /* 更新价格 */
    public function refreshPrice($project_id,$pm_type,$ave_price){
        $table = $this->getPmTypeTable($pm_type);
        //echo 'update fc_project set red_'.$table.'_price_average='.$ave_price.' where id='.$project_id;exit;
        $rlt = $this->pdo->doSql('update fc_project set red_'.$table.'_price_average='.$ave_price.' where id='.$project_id);
        return $rlt;
    }

    /* 记录用户查看过房源电话 */
    public function showTel($esf_id,$user){
        $sysLog = new SysLog();
        $rlt = $sysLog->actionLog($esf_id,$user['user_id'],'浏览了房源电话','fc_esf','showtel');//系统日志
        return $rlt;
    }

    /* 记录用户查看过房源房号 */
    public function showHouseNo($esf_id,$user){
        $sysLog = new SysLog();
        $rlt = $sysLog->actionLog($esf_id,$user['user_id'],'查看了房源房号','fc_esf','showhouseno');//系统日志
        return $rlt;
    }

    /* 根据物业类型获取表 */
    public function getPmTypeTable($pm_type){
        $table = 'house';
        switch($pm_type){
            case '22301'://别墅
                $table ='villa';
                break;
            case '22304'://商业
                $table ='business';
                break;
            case '22305'://写字楼
                $table ='office';
                break;
            default:
                $table ='house';
                break;
        }
        return $table;
    }



}
